import json
import os
import importlib


def unit_load():
    race_list = ["space_marines", "ultramarines", "world_eaters"]
    base_race_dict = dict()
    unit_dict = dict()

    path_name = "units/races"
    module_files = [f[:-3] for f in os.listdir(path_name) if f.endswith('.py') and f != '__init__.py']

    for race_name in module_files:
        race = importlib.import_module("{0}.{1}".format(path_name.replace("/", "."), race_name))
        for name, obj in vars(race).items():
            if isinstance(obj, type):
                base_race_dict[race_name] = obj

    for race in race_list:
        unit_dict[race] = dict()
        with open("units/datasheets.json", "r", encoding="utf-8") as datasheets:
            data = json.load(datasheets)

        for unit in data[race]:
            unit_dict[race][unit["name"]] = type(unit["class_name"], (base_race_dict[race],), {})
            for k, v in unit["attrs"].items():
                setattr(unit_dict[race][unit["name"]], k, v)
    return unit_dict
